package pers.acp.test.kotlin.conf

import com.zaxxer.hikari.HikariDataSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.orm.jpa.JpaTransactionManager
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.annotation.EnableTransactionManagement
import pers.acp.test.kotlin.base.BaseJpaConfig
import java.util.*

/**
 * @since JDK 17
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    basePackages = ["pers.acp.test.kotlin.repository"],
    entityManagerFactoryRef = "entityManagerFactoryPrimary",
    transactionManagerRef = "transactionManagerPrimary"
)
class JpaPrimaryConfig @Autowired constructor(
    jpaProperties: JpaProperties,
    hibernateProperties: HibernateProperties
) : BaseJpaConfig(jpaProperties, hibernateProperties) {
    @Primary
    @Bean("dataSourcePrimary")
    @ConfigurationProperties(prefix = "spring.datasource")
    fun primaryDataSource(): HikariDataSource {
        return HikariDataSource()
    }

    @Primary
    @Bean(name = ["entityManagerFactoryPrimary"])
    fun entityManagerFactoryPrimary(): LocalContainerEntityManagerFactoryBean {
        val em: LocalContainerEntityManagerFactoryBean = buildEntityManagerFactory(primaryDataSource())
        em.persistenceUnitName = "persistenceUnitPrimary"
        return em
    }

    @Primary
    @Bean(name = ["transactionManagerPrimary"])
    fun transactionManagerPrimary(): PlatformTransactionManager {
        return JpaTransactionManager(Objects.requireNonNull(entityManagerFactoryPrimary().getObject()))
    }
}
